<?php

/**

 * 关注收藏模型

 * @author maniac

 */

namespace app\common\model;



use app\common\model\Collection as CollectionModel;

class Collection extends SoftDel

{

    public $tableName = '关注收藏';           // 数据表名称

    public $logId     = ['id'];      // 日志操作相关标识
	public $softId    = 1;                    // 软删除标识
	protected $autoWriteTimestamp = true;     // 自动写入时间戳

    public function fields()
    {
        $fields = 'id,userid,data_id,data_type,create_time,list_order';
        return $fields;
    }
	/*
	 * 获取商品信息
		* */
	public function getGoodsAttr($val,$data){
		$field = 'id,store_id,goods_name,goods_sn,goods_unit,market_price,sale_price,goods_stock,goods_thumb_id,goods_album,goods_spec_format,goods_detail,collect_nums,comment_stars,evaluate_nums,is_sale,max_purchase_nums,min_purchase_nums,sale_time,category_id,type,goods_type';
		$append = [ 'goods_spec_format_array', 'cost_jifen', 'image_uri', 'goods_album_detail', 'is_sale_txt', 'sale_time_txt', 'total_sale_nums', 'attr_value'];
		$content = Goods::field($field)->append($append)->where('id',$data['data_id'])->find();
		return $content;
	}
	/*
	 * 获取商铺信息
		* */
	public function getShopAttr($val,$data){
		$field = 'id,name,photos,image_uri,content,category_id';
		$append = ['image_uri_str','photos_pics','category_name'];
		$content = Stores::field($field)->append($append)->where('id',$data['data_id'])->find();
		return $content;
	}
	/*
		 * 添加关注/收藏
		 *
		 * $userId      int     用户ID
		 * $data        int     收藏数据
		 * */
	public function add_collection($userId, $data)
	{
		if (!$data['data_id']) {
			exception('data_id不能为空');
		}
		$data['data_type'] = $data['data_type'] ? $data['data_type'] : 'product';
		$where = [
			['userid', 'eq', $userId],
			['data_id', 'eq', $data['data_id']],
			['data_type', 'eq', $data['data_type']],//商品product视频video论文paper分享share资料content
		];
		$col = CollectionModel::field('id')->where($where)->find();
		if ($col) {//判断是否收藏过 如果是取消收藏
			CollectionModel::destroy($col['id'], true);//取消收藏
			return 1;
		} else {
			$data['userid'] = $userId;

			$info = CollectionModel::create($data);//收藏
			if ($info) {
				return 1;
			}
		}
		return false;

	}

	/*
	 * 收藏记录
	 *
	 * $userId      int     用户ID
	 * $type        int     类型      商品product商户shop
	 * */
	public function collection_list($userId, $type, $page = 0, $limit = 0)
	{
		$where = [];//条件
		$addend = [];//追加字段
		$order = 'id';//排序
		$where = [
			['userid', 'eq', $userId],
			['data_type', 'eq', $type]
		];
		switch ($type) {
			case 0:
				$addend = ['goods'];
				break;
			case 1:
				$addend = ['shop'];
				break;
		}
		$col_mod = new CollectionModel();
		$list = $col_mod->getList($where, '', $order, $addend, $page, $limit);
		return $list;
	}

}

